<%-- 
    Document   : components
    Created on : 11.03.2014, 16:42:33
    Author     : Corvus 11
--%>

<%@ taglib prefix="tiles" uri="http://tiles.apache.org/tags-tiles" %>
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<tiles:insertDefinition name="baseTemplate">
    
    <tiles:putAttribute name="postLinks">
        <script type="text/javascript" src="js/components/dialog-component-properties.js"></script>
        <script type="text/javascript" src="js/components/dialog-new-component.js"></script>
        <script type="text/javascript" src="js/components/dialog-delete-component.js"></script>
        <script type="text/javascript" src="js/components/dialog-move-to-employee.js"></script>
        <script type="text/javascript" src="js/components/dialog-move-to-office.js"></script>
        <script type="text/javascript" src="js/jquery.optionTree.js"></script>
    </tiles:putAttribute>
    
    <tiles:putAttribute name="title">
        <title>Оборудование</title>
    </tiles:putAttribute>
    <tiles:putAttribute name="selectedItem">
            <input type="hidden" id="menu_selected_item" value="menuitem_components">
    </tiles:putAttribute>

    <tiles:putAttribute name="body">
        <div class="container" id="components_container">
            <div id="components_type_container">
                <h3>Типы оборудования</h3>
                <p></p>
                <div id="component_type_tree">
                    
                </div>
                
                <p></p>
                <a href="./editComponents" id="edit_component_types" class="button bg-blue fg-white">Настроить типы комплектующих...</a>
            </div>
            <div id="components_table_container">
                <p></p>
                
                
                    <div>
                        <sec:authorize access="hasRole('ROLE_MANAGER')">
                        <button id="addComponent" class="button bg-green fg-white"  onclick="dialogNewComponent();" >
                            <i class="icon-plus-2 on-left"></i>Добавить
                        </button>
                        </sec:authorize>
                        <button id="editComponent" class="button bg-darkBlue fg-white" onclick="dialogComponentProperties();">
                            <i class="icon-cog on-left"></i>Описание...
                        </button>
                        <sec:authorize access="hasRole('ROLE_MANAGER')">
                        <div class="button-dropdown">
                            <button id="component_status" class="button dropdown-toggle bg-darkBlue fg-white">
                                Состояние
                            </button>
                            <ul class="dropdown-menu bg-darkBlue fg-white" data-role="dropdown">
                                <li><a onclick="setStatus('0');"><i class="icon-checkmark on-left"></i>Исправен</a></li>
                                <li><a onclick="setStatus('X');"><i class="icon-cancel-2 on-left"></i>Неисправен</a></li>
                                <li><a onclick="setStatus('R');"><i class="icon-wrench on-left"></i>В ремонте</a></li>
                            </ul>
                        </div>
                        <button id="remove_component" class="button bg-darkBlue fg-white" onclick="setRemoved();">
                            <i class="icon-cancel on-left"></i>Списать
                        </button>
                        <div class="button-dropdown">
                            <button id="move_employee" class="button dropdown-toggle bg-darkBlue fg-white">
                                Пользователь
                            </button>
                            <ul class="dropdown-menu bg-darkBlue fg-white" data-role="dropdown">
                                <li><a onclick="dialogMoveToEmployee(true);"><i class="icon-user on-left"></i>Сменить</a></li>
                                <li><a onclick="dialogMoveToEmployee(false);"><i class="icon-cancel-2 on-left"></i>Убрать</a></li>
                            </ul>
                        </div>
                        <button id="move_office" class="button bg-darkBlue fg-white" onclick="dialogChangeOffice();">
                            <i class="icon-home on-left"></i>Сменить офис
                        </button>
                        <!--<button id="move_complect" class="button bg-amber fg-white" onclick="">
                            <i class="icon-wrench on-left"></i>Комплектация...
                        </button>-->
                        </sec:authorize>
                    </div>
                
                <table id="component_table" class="table hovered striped dataTable bordered">
                    <thead>
                        <tr role="row">
                            <th class="text-left">Модель</th>
                            <th class="text-left">Серийный №</th>
                            <th class="text-left">Пользователь</th>
                            <th class="text-left">Состояние</th>
                            <th class="text-left">Офис</th>
                            <th class="text-left">Окончание гарантии</th>
                        </tr>
                    </thead>
                    <tbody>
                    </tbody>
                </table>
                
                <script type="text/javascript">
                    
                    $(document).ready(function() {
                        blockButtons(true);
                        
                        loadTypeTree();
                        
                        $('#component_type_tree a#0').addClass('active');
                        $('#component_type_tree a').each(function(ind,element){
                            element.onclick = function(e){
                              reloadTable();
                            };
                            var $elem = $(element);
                            $elem.css({
                               paddingLeft: ($elem.parents("ul").length-1) * 20 
                            });
                        });
                        
                        $('#component_table').dataTable({
                            "bFilter":false,
                            "bServerSide":true,
                            "sAjaxSource": './a_get_component_table_data',
                            "bInfo":false,
                            "oLanguage": {
                                "sUrl": "./resources/datatables.russian.txt",
                            },
                            "aoColumns": [
                                {"mData":'model'},
                                {"mData":'serial'},
                                {"mData":'surnameNamePatronymic'},
                                {"mData":'status'},
                                {"mData":'officeName', "sWidth":'12%'},
                                {"mData":'warrantyEnd'}
                            ],
                            "fnServerParams": function(aoData) {
                                var selectedCat = $('#component_type_tree a.active')[0].id;
                                aoData.push({
                                    "name":"cathegory", 
                                    "value": selectedCat
                                });
                            },
                            "fnRowCallback": function(nRow, aData, iDisplayIndex) {
                        
                                if (aData.deleted === true) {
                                    $(nRow).addClass("deleted");
                                    $(nRow).children()[3].innerHTML = "Списано";
                                }
                                
                                nRow.onclick = function(e) {
                                    $('#component_table tbody tr').removeClass('row_selected');
                                    
                                    var pNode = $(e.target).closest('tr');
                                    
                                    $(pNode).toggleClass('row_selected');
                                    
                                    var row = $('#component_table tr.row_selected');
                                    blockButtons(false, $(row).hasClass('deleted'));
                                    
                                };
                            },
                            "fnDrawCallback": function( oSettings ) {
                                  $('#component_table_paginate span span').css({"float": 'left', "margin":'0px 3px'})
                            }
                        });
                        
                    });
                    
                    function loadTypeTree() {
                        $.ajax({
                            "url":'a_get_type_tree',
                            "type":'GET',
                            "dataType":'json',
                            "async":false,
                            "success": function(json) {
                                
                                var mainNode = document.createElement('ul');
                                mainNode.className = 'treeview';
                                mainNode.setAttribute('data-role','treeview');
                                var li = createTypeTreeNode(json, false);
                                mainNode.appendChild(li);
                                document.getElementById('component_type_tree').appendChild(mainNode);
                            }
                        });
                    }
                    
                    function createTypeTreeNode(json, collapsed) {
                        var li = document.createElement('li');
                        if (collapsed) li.className = 'node collapsed';
                            else li.className = 'node';
                        var jSubtypes = json.typeSubtypes;
                        var a = document.createElement('a');
                        if (jSubtypes.length > 0) {
                            var span = document.createElement('span');
                            span.className = 'node-toggle';
                            a.appendChild(span);
                        }
                        a.id = json.typeId;
                        a.innerHTML += json.typeName;
                        li.appendChild(a);
                        if (jSubtypes.length > 0) {
                            var ul = document.createElement('ul');
                            li.appendChild(ul);
                            for(var i = 0; i < jSubtypes.length; i++) {
                                ul.appendChild(createTypeTreeNode(jSubtypes[i],true));
                            }
                        }
                        return li;
                    }
                    
                    function blockButtons(block, deleted) {
                        var button = document.getElementById('editComponent');
                        if (button != undefined) button.disabled = block;
                        button = document.getElementById('component_status');
                        if (button != undefined) button.disabled = block || deleted;
                        button = document.getElementById('remove_component');
                        if (button != undefined) button.disabled = block || deleted;
                        button = document.getElementById('move_employee');
                        if (button != undefined) button.disabled = block || deleted;
                        button = document.getElementById('move_office');
                        if (button != undefined) button.disabled = block || deleted;
                        button = document.getElementById('move_complect');
                        if (button != undefined) button.disabled = block || deleted;
                    }
                    
                    /*function reloadTable() {
                        var table = $('#component_table').dataTable();
                        table.fnDraw();
                    }*/
                    
                    function setStatus(statusStr) {
                        var selectedRow = $('.row_selected')[0];
                        if (selectedRow == undefined) return;
                        var selectedStatus = selectedRow.childNodes[3].textContent;
                        
                        if ((statusStr === 'X' && selectedStatus === 'Неисправно') ||
                            (statusStr === '0' && selectedStatus === 'Исправно') ||
                            (statusStr === 'R' && selectedStatus === 'В ремонте')) return;
                        
                        
                        $.Dialog({
                            "title": "Выберите дату",
                            "draggable": true,
                            "content": "<div id='select_date_main' class='dialog-content'>"+
                                       "    <input id='status_str' type='hidden'>" +
                                       "    <div id='select_date_div' class='input-control text' data-role='datepicker' data-locale='ru'>" +
                                       "        <input id='select_date_data' type='text'>" +
                                       "        <button type='button' class='btn-date'></button>" +
                                       "    </div>" +
                                       "    <div>" +
                                       "        <input id='select_date_ok' class='place-right' name='select_date_ok' value='Ok' type='button' onclick='submitComponentStatus();'>" +
                                       "    </div>" +
                                       "</div>",
                            "onShow" : function() {
                                setDatepickerDefDate('select_date_data');
                                $('#status_str').val(statusStr);
                            },
                            "width" : 200,
                            "height" : 125
                        });
                        
                        
                    }
                    
                    function submitComponentStatus() {
                        var selectedRow = $('.row_selected')[0];
                        var statusStr = $('#status_str').val();
                        var date = $('#select_date_data').val();
                        $.ajax({
                           "url":'a_set_component_status',
                           "data":{"compId":selectedRow.id,"newStatus":statusStr, "date":date},
                           "type":'POST',
                           "dataType":'json',
                           "success": function(json) {
                               if (json.errorVal === 'OK') {
                                    switch(statusStr) {
                                        case '0': selectedRow.childNodes[3].textContent = 'Исправно'; break;
                                        case 'X': selectedRow.childNodes[3].textContent = 'Неисправно'; break;
                                        case 'R': selectedRow.childNodes[3].textContent = 'В ремонте'; break;
                                    }
                                    $.Notify({
                                         "content": "Состояние изменено.",
                                         "timeout": 5000
                                    });
                                    $.Dialog.close();
                                    var table = $('#component_table').dataTable();
                                    table.fnDraw();
                               } else {
                                   $('#select_date_div').addClass('error-state');
                                   var message;
                                   if (json.errorVal === 'Error_date_busy')
                                       message = "История оборудования для выбранной даты уже заполнена.";
                                   else message = "Нельзя использовать будущую дату.";
                                   $.Notify({
                                         "content": message,
                                         "style": {"background": 'darkred', "color": 'white', "font": 'bold'},
                                         "timeout": 8000
                                    });
                               }
                           }    
                        });
                    }
                    
                    function setRemoved() {
                        var selectedRow = $('#component_table tr.row_selected')[0];
                        var id = selectedRow.id;
                        
                        if (!$(selectedRow).hasClass('deleted')) {
                            dialogDeleteComponent(id);
                        }
                    }
                </script>
            </div>
        </div>
    </tiles:putAttribute>
</tiles:insertDefinition>